<?php
session_start();

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
	header('Location: ./');
}
$paperId = (int)$_GET['id'];

// Connect to the DB.
require_once 'include/config.lib.php';
require_once 'include/database.lib.php';

ConnectToDB();

// Load summary data about the paper.
$paperReq = DBExecute('	SELECT title, abstract, rating.* FROM bibtex AS b
						LEFT JOIN (
						SELECT r.bibtexid, AVG(rr.clarity) AS clarity, AVG(rr.structure) AS structure,
							AVG(rr.novelty) AS novelty, AVG(rr.usefulness) AS usefulness, AVG(rr.total) AS total
						FROM resource AS r, rateresource AS rr
						LEFT JOIN authoring ON authoring.resourceid=rr.resourceid
						LEFT JOIN person ON person.id=authoring.personid
							WHERE r.id=rr.resourceid AND r.bibtexid=? GROUP BY r.bibtexid
						) AS rating ON b.id=rating.bibtexid
						WHERE b.id=?', array($paperId, $paperId));

$paper = $paperReq->fetchAssocRow();
$ratings = array($paper['USEFULNESS'] * 10, $paper['STRUCTURE'] * 10, $paper['CLARITY'] * 10, $paper['NOVELTY'] * 10, $paper['TOTAL'] * 10);

//resource IDs associated with the bibtexid
$resourceIDs = DBExecute(' SELECT r.id AS resourceID FROM resource r
						 WHERE r.bibtexid = ?', array($paperId));

$authorsReq = DBExecute(' SELECT unique p.name AS author FROM resource r, person p, authoring a
						WHERE r.bibtexid = ? and a.resourceid = r.id AND a.personid = p.id', array($paperId));

$personName = "";
$userName = "";
$personID = "";
$userIsAuthor = false;

if(isset($_SESSION["accountNo"])){
    //get the user's username
	$userName = $_SESSION["accountNo"];
    
    //get the user's real name
    $name = DBExecute('SELECT person.name AS name
                        FROM person WHERE person.username = ?', $userName); //actual name
	$personNameRow = $name->fetchAssocRow();
	$personName = $personNameRow['NAME'];	
    
    //get the user's personID
    $ID = DBExecute('SELECT person.id AS id 
						FROM person WHERE person.username = ?', $userName);
	$personIDRow = $ID->fetchAssocRow();
	$personID = $personIDRow['ID'];
}

$authors = '';	//authors of the publication
while ( $keyrow = $authorsReq->fetchAssocRow()) {
	$authors .= $keyrow['AUTHOR'] . '; ';
	
	if($keyrow['AUTHOR'] == $personName)  // check if the user is alrerady listed as an author
		$userIsAuthor = true;	
} 

// Load tags about the paper.
//$tagReq = DBExecute('SELECT label FROM tagging AS t, resource AS r WHERE t.resourceid=r.id AND r.bibtexid=?', $paperId);
$tagReq = DBExecute('SELECT label,num FROM tagcount AS t, resource AS r WHERE t.resourceid=r.id AND r.bibtexid=?', $paperId);
$tags = array();

// currently we have taggings that don't have associated tagcount (tagcount is created after some rows are added to tagging)
//this part gets tags and their frequency, if any tag is assigned after creation of the tagcount table 
$tagcountFilled = false;
while ($row = $tagReq->fetchAssocRow()) {
	$tagcountFilled = true;
	$tags[trim($row['LABEL'])] = $row['NUM'];
}
// if this resource has no tags in tagcount table, we look into tagging
// TODO, after clearing database from inconsistency between tagging and tagcount, this should be eliminated
if( !$tagcountFilled ){
	$tagReq = DBExecute('SELECT label FROM tagging AS t, resource AS r WHERE t.resourceid=r.id AND r.bibtexid=?', $paperId);
	while ($row = $tagReq->fetchAssocRow()) {
	// TODO: there should be frequency of the tag appearances.
	$tags[trim($row['LABEL'])] = rand(1, 4);
	}
}
arsort($tags);

// Load keywords:
$keywordsReq = DBExecute('SELECT label FROM keywords WHERE bibtexid=?', $paperId);
$keywords = '';
while ( $keyrow = $keywordsReq->fetchAssocRow()) {
	$keywords .= $keyrow['LABEL'] . '; ';
} 

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/template.css" />
<link rel="stylesheet" type="text/css" href="css/paper_view.css" />
<link rel="stylesheet" type="text/css" href="css/conv_styles.css" />
<link rel="stylesheet" type="text/css" href="css/network_styles.css" />
<!-- third party scripts -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="third_party/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="third_party/jit.js"></script>
<!--[if IE]><script language="javascript" type="text/javascript" src="third_party/excanvas.js"></script><![endif]-->
<!-- project specific scripts -->
<script type="text/javascript" src="js/system.js"></script>
<script type="text/javascript" src="js/timechart.js"></script>
<script type="text/javascript" src="js/conversation.js"></script>
<script type="text/javascript" src="js/network.js"></script>
<script type="text/javascript" src="js/network_custom.js"></script>
<script type='text/javascript'>
var paperId = <?php echo $paperId; ?>;
var commentsWidget = null;
var networkWidget = null;
var timechartWidget = null;

function Toggle(showId, hideId) {
	document.getElementById(showId).style.display = "block";
	document.getElementById(hideId).style.display = "none";
}

function GInitialize() {
	timechartWidget = new TimeChart(document.getElementById("timeline-section"),
																	{ link: 'javascript:commentsWidget.highlightComment({id})' });
	RequestData("data.php", { "requestType": "timechart", "id": paperId }, timechartWidget.update);
}

google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(GInitialize);

function FilterByPeople(peopleIds) {
	commentsWidget.filterThreadsByPeople(peopleIds);
	timechartWidget.filterByPeople(peopleIds);
}

function OnLoad() {
	commentsWidget = new Comments(document.getElementById("comments-container"));
	RequestData("data.php", { "requestType": "commentTree", "id": paperId }, commentsWidget.update_comments);
	networkWidget = new Network("network", FilterByPeople, new NetworkCustom('paper'));
	RequestData("data.php", { "requestType": "relationships", "id": paperId }, networkWidget.update);
}

</script>
<title>Forum</title>
</head>
<body onload="OnLoad();">
<?php //to determine whether a user has logged in or not, which will output different buttons
if(isset($_SESSION["accountNo"]))	{	$inorout = "controller/logout.php";	$display = "Log out";}
else	{	$inorout = "login.php";	$display = "Log in";}


?>
<div id="body-wrapper">
<?php include_once 'static/header.php'; ?>
<div id="body">
	<!-- START SECTION: summary -->
	<div id="summary-section" class="section">	
		<img id="rating-chart" src="http://chart.apis.google.com/chart?cht=bhs&chs=250x120&chxt=x,y&chd=t:<?php echo implode(',', $ratings); ?>&chxl=0:|0|5|10|1:|usefulness|structure|clarity|novelty|total&chbh=15" />
		<table id="stat" class="info">
			<tr>
				<td><h1><?php echo isset($paper['TITLE']) ? $paper['TITLE'] : 'Title not available'; ?></h1></td>
			</tr>
			<tr>
				<td><?php echo isset($paper['ABSTRACT']) ? $paper['ABSTRACT'] : $paper['URL']; ?></td>
			</tr>
			<tr>
				<td><?php echo (isset($keywords) && $keywords != '') 
						?
					 '<b>Keywords: </b> '.$keywords					 
					 : ' - Keywords not provided'; ?></td>
			</tr>
			<tr>
				<td><?php 	if(isset($_POST['SubmitCheck']) && ($userIsAuthor == false)){ 	//If user was added, add them to the display
								$authors .= " " . $personName;
							}
							echo isset($authors['AUTHOR']) ? '<b>Author(s): </b>' .$authors : ' - Author not available'; ?></td>
			</tr>
			<tr>
			</tr>
		</table>
	</div>
		<a class = "section" onclick="javascript:showElement('claimpaper')">Are you an author of this publication?</a>
		<div id="claimpaper" style="display:none" class = "section">
			<?php

			if(isset($_SESSION["accountNo"])){	//check if user is signed in
 				if(isset($_POST['SubmitCheck'])) {	//Test if the form has already been submitted
					if($userIsAuthor == false) {	//check if the user is already listed as an author
						$resourceID = '';
						
						while ( $row = $resourceIDs->fetchAssocRow()) {
							$resourceID = $row['RESOURCEID'];
						 
						$insert = DBExecute("INSERT INTO authoring (personid,resourceid)
											VALUES (?, ?)", array($personID, $resourceID));
						}
			         	echo "You have been added as an author to this publication under the name: '".$personName."'";
					}
			     	else{
			     		echo "You are already listed as an author of this publication under the name: '".$personName."'";
			     	}
 				}

				?>
				<form id="claimPub" action="<?=$SERVER["PHP_SELF"]?>" method="post">
					<tr><th>Add your name the the authors of this publication:</td></tr>
					<input type="hidden" name="SubmitCheck" value="sent">
					<input type="submit" class="button" value="Claim Paper" />
				</form>
				<?php		
			}
			else 
			{
				echo 'Please sign in to claim a paper';
			}
			?>
		</div>
	<!-- END SECTION: summary -->
	
	<!-- START SECTION: timeline -->
	<div id="timeline-section" class="section"><div id="timeline-chart"></div></div>
	<!-- END SECTION: summary -->
	
	<!-- START SECTION: social graph -->
	<div id="network-section" class="left-section"><div id="network"></div><a href="#network" class="button" onclick="javascript:showElement('collapse')"><span id = "guidance">Network Guidance</span></a><div id="network-guide"></div></div>
	<!-- END SECTION: social graph -->
	
	<!-- START SECTION: filters -->
	<div id="filter-section" class="right-section"><div id="filter">
		<div id="tags-simple" class="tags">
			<ul>
				<?php
				// Show top 5 tags.
				$count = 0;
				foreach ($tags as $tag => $freq) {
					echo '<li><a href="#">', $tag, '</a></li>';
					$count++;
					if ($count == 5) break;
				} ?>
				<li class="highlight"><a href="javascript:Toggle('tags-full', 'tags-simple')">expand</a></li>
			</ul>
		</div>
		<div id="tags-full" class="tags">
			<ul> 
				<?php
				foreach ($tags as $tag => $freq) {
					echo '<li class="tag', $freq, '"><a href="#">', $tag, '</a></li>';
				} ?>
				<li class="highlight"><a href="javascript:Toggle('tags-simple', 'tags-full')">collapse</a></li>
			</ul>
		</div>
	</div></div>
	<!-- END SECTION: filters -->
	
	<!-- START SECTION: threaded control -->
	<div id="comment-section" class="right-section">
		<ul class="horizontal" id="sort-by">
			<li><b>Sort by</b></li>
			<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byNameAsc)">Names A-Z</li>
			<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byRateDesc)">Cluster by polarity</li>
			<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byDateDesc)">Recent first</li>
			<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byDateAsc)">Recent Last</li>
		</ul>
		<div id="comments-container"></div>
	</div>
	<!-- END SECTION: threaded control -->
</div>
<?php include_once 'static/footer.html'; ?>
</div>
</body>
</html>
